from jili.core import moheengine as mh
from jili.trade.constants import adapter_subjects
class AdapterFrame:
    def __init__(self,config={}):
        self.config=config

        self.adpatermap = {}
    """
    self.cmdmap=dict(login="Login",logout="Logout")
    def __getbrokercmd(self,cmds):
        if cmds in self.cmdmap.keys():
            cmds = self.cmdmap[cmds]
        return cmds
    """

    def loadcore(self,tradecore):
        self.tradecore=tradecore
        self.coretype=tradecore.coretype
        self.up=adapter_subjects[self.coretype]["up"]
        self.down=adapter_subjects[self.coretype]["down"]
        print("tradecore version",tradecore.getversion())
        print("tradecore up-dowm", self.up,self.down)
    def run(self,config={}):
        if config:
            self.config.update(config)
        mh.subscribe(self.__onmsg, self.up, "")

    # class __dir__(),getattr(a,"call")("i am siiii"),hasattr(a,"call2")
    def __trycall(self,msg):
        """
        m={}
        m["0"]="acknotify"  #msgtype
        m["1"]=str(msg["s"]["pid"])  #subject
        m["2"]={cmd:,data:}   #data必有 cmd,data  可有  requstid，rsqid,islast,
        t=msg["s"]
        t["isreply"]=False
        m["s"]=t
        m["e"]=getsource()
        """
        #print("onmsg:", msg)
        data = msg["2"]
        # print("data-1",data)
        cmd = data["cmd"]
        investorid = msg["1"]
        if investorid in self.adpatermap.keys():  # 是否初始化接口
            adpater = self.adpatermap[investorid]
            if adpater.isLogined:  # 是否login,是执行命令调用
                if hasattr(adpater, cmd):
                    getattr(adpater, cmd)(data)
                else:
                    self.senderror(data["RequestID"], investorid, "no this cmd,please check you code or cmd first")
            else:  # 否，是否login cmd
                if cmd in ["login", "Login"]:  # 是否登陆命令
                    ret=adpater.login(data)
                    if ret[0]!=0:
                        self.senderror(data["RequestID"], investorid, ret[1])
                else:  # 否回复非法
                    self.senderror(data["RequestID"], investorid, "no login,please login first")
        else:  # 没有则初始化
            if cmd in ["login", "Login"]:  # 是否登陆命令
                config = self.config[self.coretype]
                brokerid = data["BrokerID"]
                config["BrokerID"]=brokerid
                config["login_data"]=data
                trader = self.tradecore.create(investorid, config)
                trader.setInvestorID(investorid)
                ret = trader.login(data)
                if ret[0] != 0:
                    self.senderror(data["RequestID"], investorid, ret[1])
                else:
                    self.senderror[investorid] = trader
            else:  # 否回复非法
                self.senderror(data["RequestID"], investorid, "no login,please login first")
    def __onmsg(self,msg):
        try:
            self.__trycall(msg)
        except Exception as e:
            try:
                data = msg["2"]
                self.senderror(data["RequestID"], data["InvestorID"], e.args[0])
                print("onmsg sysyerror:", e)
            except Exception as e:
                print(e)
    def senderror(self,reuestid, investorid, info, cmd="OnSysError"):
        rspinfo = dict(ErrorID=1, ErrorMsg="error")
        if isinstance(info, dict):
            rspinfo.update(info)
        else:
            rspinfo["ErrorMsg"] = info
        msg = {}
        msg["RspInfo"] = rspinfo
        msg["RequestID"] = reuestid
        msg["cmd"] = cmd
        msg["IsLast"] = True
        msg["data"] = {}
        mh.safesend(self.down, investorid, msg)